﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace EpiMapit
{
	class LevelOfDetail
	{
        private CaseSetGroup caseSets;

        public LevelOfDetail(CaseSetGroup caseSets)
		{
			this.caseSets = caseSets;
		}

		public float FindTheClosest(out CaseSet case1, out CaseSet case2)
		{
			float distance = float.MaxValue;

			case1 = null;
			case2 = null;
			foreach (var caseSet1 in caseSets)
			{
				foreach (var caseSet2 in caseSets)
				{
					if (caseSet1 != caseSet2)
					{
						float newDistance = caseSet1.DistanceFrom(caseSet2);
						if (newDistance < distance)
						{
							distance = newDistance;
							case1 = caseSet1;
							case2 = caseSet2;
						}
					}
				}
			}
			return distance;
		}

		public bool JoinTheClosest(float maxDistance)
		{
			CaseSet case1, case2;
			float distance = FindTheClosest(out case1, out case2);
			if (distance < maxDistance && case1 != null)
			{
				caseSets.Remove(case2);
				case1.JoinWith(case2);
				return true;
			}
			return false;
		}

		public bool Cluster(float maxDistance)
		{
            var res = false;
			while(JoinTheClosest(maxDistance))
                res = true;
			
			var minSize = CaseSets.Min(x => x.TotalSize());
			
			var unit = maxDistance;

			caseSets.Unit = unit;
            caseSets.MaxDistance = maxDistance; 
            
            return res;
        }

		public CaseSetGroup CaseSets
		{
			get { return caseSets; }
		}
	}
}
